import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/net/authorization_connect.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:lpinyin/lpinyin.dart';

import '../../models/authoization_city_entity.dart';
import '../../widget/custom_app_bar.dart';
import 'authorization_page_controller.dart';

class BuildCityPage extends StatefulWidget {
  const BuildCityPage({super.key});

  @override
  State<StatefulWidget> createState() => _BuildCityState();
}

class _BuildCityState extends State<BuildCityPage> {
  List<CityModel> cityList = [];
  double susItemHeight = 40;
  late AuthorizationConnect connect;

  @override
  void initState() {
    super.initState();
    connect = Get.find<AuthorizationConnect>();
    loadData();
  }

  /// 加载城市列表
  void loadData() async {
    var response = await connect.getCityList();
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.success) {
      for (var cityName in response.obj) {
        cityList.add(CityModel(name: cityName));
      }
      _handleList(cityList);
    }
  }

  /// 右侧悬浮列表
  void _handleList(List<CityModel> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp('[A-Z]').hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = '#';
      }
    }
    //A-Z 分类.
    SuspensionUtil.sortListBySuspensionTag(list);
    //显示悬停Header.
    SuspensionUtil.setShowSuspensionStatus(cityList);

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar("请选择城市"),
      body: AzListView(
        data: cityList,
        itemCount: cityList.length,

        ///悬浮列表样式
        indexBarOptions: IndexBarOptions(
          needRebuild: true,
          ignoreDragCancel: true,
          downTextStyle: TextStyle(fontSize: 20.sp, color: Colors.white),
          downItemDecoration: const BoxDecoration(
              shape: BoxShape.circle, color: Color(0xFF1774E0)),
          indexHintWidth: 56.h,
          indexHintHeight: 56.h,
          indexHintTextStyle: TextStyle(
              fontSize: 28.sp, color: const Color(0xFF434649).withOpacity(0.5)),
          indexHintDecoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/authorization_down_icon.png"),
              fit: BoxFit.contain,
            ),
          ),
          indexHintAlignment: Alignment.centerRight,
          indexHintChildAlignment: const Alignment(-0.25, 0.0),
          indexHintOffset: Offset(-10.w, 0),
        ),
        itemBuilder: (BuildContext context, int index) {
          CityModel model = cityList[index];
          return getListItem(model);
        },
        physics: const BouncingScrollPhysics(),
        susItemBuilder: (BuildContext context, int index) {
          CityModel model = cityList[index];
          return getSusItem(model.getSuspensionTag());
        },
      ),
    );
  }

  Widget getListItem(CityModel model) {
    AuthorizationController controller = Get.find<AuthorizationController>();
    return InkWell(
      onTap: () => controller.setCity(model.name),
      child: Container(
        alignment: Alignment.centerLeft,
        height: 96.h,
        padding: EdgeInsets.only(left: 32.w),
        decoration: const BoxDecoration(
            color: Colors.white,
            border: Border(
                bottom: BorderSide(width: 1.0, color: Color(0xFFF4F5F6)))),
        child: Text(
          model.name,
          style: TextStyle(fontSize: 32.sp),
        ),
      ),
    );
  }

  Widget getSusItem(String tag) {
    return Container(
      height: 58.h,
      width: 1.sw,
      padding: const EdgeInsets.only(left: 16.0),
      color: const Color(0xFFF3F4F5),
      alignment: Alignment.bottomLeft,
      child: Text(
        tag,
        softWrap: false,
        style: TextStyle(
          fontSize: 24.sp,
          color: const Color(0xFFCECECE),
        ),
      ),
    );
  }
}
